package src.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.text.SimpleDateFormat;

/**
 * @author jack,wu
 * @version 1.0
 * @date 2020-06-06
 */
public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if (msg instanceof HttpRequest) {
            System.out.println("pipeline hashcode ：" + ctx.pipeline().hashCode());
            System.out.println("MyHttpServerHandler hashcode ：" + this.hashCode());
            System.out.println("msg 类型：" + msg.getClass());
            System.out.println("远程客户端地址：" + ctx.channel().remoteAddress());
            HttpRequest request = (HttpRequest) msg;
            URI uri = new URI(request.uri());
            // 响应拦截
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求 favicon.ico 不做响应");
                return;
            }
            ByteBuf content = Unpooled.copiedBuffer("My Server", CharsetUtil.UTF_8);
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
